__author__ = 'Shoohy'

import json
import time

from google.appengine.api import users
import os

import urlparse
from oauth2client.appengine import OAuth2Decorator
import httplib2
from apiclient import discovery
from google.appengine.api import memcache
import settings

from model_child import Child
from model_att import Att
from model_KG import Kindergarten
from model_message import Message
from model_gcm import GCM

from google.appengine.ext import ndb

import jinja2
import webapp2


# user login authentication
global decorator
decorator = OAuth2Decorator(client_id   = settings.CLIENT_ID,
                            client_secret=settings.CLIENT_SECRET,
                            scope       =settings.SCOPE)

http = httplib2.Http(memcache)
service = discovery.build('oauth2', 'v2')

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape','jinja2.ext.do'],
    autoescape=True)

KG_ID = ''

class setUp(webapp2.RequestHandler):
    #user setup
    def setUser(self):
        global KG_ID
        user = users.get_current_user()
        if user:
            KG_ID = user.email()
        else:
           self.redirect('/welcome')
           return

    # handles rendering of html page
    def render(self, link):
        template = JINJA_ENVIRONMENT.get_template(link)
        self.response.write(template.render(self.template_values))

    # set up attendance information for KG children
    def attendanceInfo(self):
        date = time.strftime("%d-%m-%Y")
        date_for_json = time.strftime("%Y-%m-%d")
        KG_children = Child.get_children_in_KG_id(KG_ID)
        childrenArr = []
        arrived = {}
        for child_id in KG_children:
            childrenArr.append(json.loads(Child.get_child_info(child_id)))

            j = {"child_id":        child_id,
                    "date" :          date_for_json}

            data_json = json.dumps(j)
            arrived[child_id] = Att.get_att_of_child_by_child_id_and_date(data_json)

        KG_info = Kindergarten.get_name_KG_CT_by_id(KG_ID)

        self.template_values = {
                'arrived':      arrived,
                'date':         date,
                'children':     childrenArr,
                'KG_info':      KG_info,
                'KG_ID':        KG_ID
            }


# redirect to proper page according to user status
class mainWeb(setUp):
    def get(self):
        user = users.get_current_user()
        if user is None:
            self.redirect('/welcome')
            return
        if(Kindergarten.check_existence_KG(user.email())):
            self.redirect('/home')
            return
        else:
            self.redirect('/addKG')
            return

# welcome page
class welcomePage(setUp):
    def get(self):
        self.template_values = {}
        self.render('htmlPages/welcome.html')

# help page
class help(webapp2.RequestHandler):
    def get(self):
        template = JINJA_ENVIRONMENT.get_template('htmlPages/help.html')
        self.response.write(template.render({}))

# home screen with updated attendance
class displayAtt(setUp):
    def get(self):
        self.setUser()
        self.attendanceInfo()
        self.render('htmlPages/att.html')

# edit children attendance
class editAtt(setUp):
    def get(self):
        self.setUser()
        self.attendanceInfo()
        self.render('htmlPages/editAtt.html')

    def post(self):
        self.setUser()
        present = self.request.get_all('att')
        date = time.strftime("%Y-%m-%d")

        KG_children = Child.get_children_in_KG_id(KG_ID)

        for child in KG_children:
            j = {"child_id":        child,
                  "date" :          date,
                  "is_arrived" :    child in present,
                  "KG_id":          KG_ID}

            Att.update_att_by_id_and_date_from_json(json.dumps(j))

        self.redirect('/home')
        return

# send message to parents about attendance
class updateParents(setUp):
    def post(self):
        self.setUser()
        date_for_json = time.strftime("%Y-%m-%d")

        j = {"date" :        date_for_json,
            "KG_id":        KG_ID}
        GCM.send_arriving_att_to_parents(json.dumps(j))
        GCM.send_not_arriving_att_to_parents(json.dumps(j))

# new kindergarten
class addKG(setUp):
    @decorator.oauth_required
    def get(self):
        self.template_values = {
            'KG_info': '',
        }

        self.render('htmlPages/newKG.html')

    def post(self):
        self.setUser()
        j = {
            'CT_first_name':    self.request.get('CT_first_name'),
            'CT_last_name':     self.request.get('CT_last_name'),
            'KG_name':          self.request.get('KG_name'),
            'phone_number':     self.request.get('phone_number'),
            'email_address':    KG_ID,
            'address':          self.request.get('address'),
        }

        Kindergarten.create_KG_from_json(json.dumps(j))

        self.redirect('/home')
        return

# new child
class addChild(setUp):
    def get(self):
        self.setUser()
        KG_info = Kindergarten.get_name_KG_CT_by_id(KG_ID)

        self.template_values = {
            'KG_info':  KG_info,
            'KG_ID':    KG_ID
        }

        self.render('htmlPages/newChild.html')

    def post(self):
        self.setUser()

        j = {
            'child_first_name':         self.request.get('first_name'),
            'child_last_name':          self.request.get('last_name'),
            'child_id':                 self.request.get('child_id'),
            'date_of_birth':            self.request.get('date_of_birth'),
            'gender':                   self.request.get('gender'),
            'phone_number':             self.request.get('home_tel'),
            'address':                  self.request.get('address'),
            'parent1_first_name':       self.request.get('parent1_first_name'),
            'parent1_last_name':        self.request.get('parent1_last_name'),
            'parent1_phone_number':     self.request.get('parent1_phone_number'),
            'parent1_email_address':    self.request.get('parent1_email_address'),
            'parent2_first_name':       self.request.get('parent2_first_name'),
            'parent2_last_name':        self.request.get('parent2_last_name'),
            'parent2_phone_number':     self.request.get('parent2_phone_number'),
            'parent2_email_address':    self.request.get('parent2_email_address'),
            'KG_id': KG_ID
        }

        if(Kindergarten.create_new_entity_from_teacher_by_json(json.dumps(j))):
            self.redirect('/home')
            return

# broadcast messages page
class displayMessages(setUp):
    def get(self):
        self.setUser()
        if not (Kindergarten.check_existence_children_in_KG(KG_ID)):
            self.redirect('/addChild')
            return
        else:
            date = time.strftime("%d-%m-%Y")

            KG_info = Kindergarten.get_name_KG_CT_by_id(KG_ID)
            data = {'KG_id': KG_ID}
            messages = Message.get_all_public_messages_by_KG_id(json.dumps(data))
            messagesArr = []
            for message in messages:
                messagesArr.append(json.loads(message))

            self.template_values = {
                'date':         date,
                'messages':     messagesArr,
                'KG_info':      KG_info,
                'KG_ID':        KG_ID
            }

            self.render('htmlPages/messages.html')

# private messages page
class privateMessages(setUp):
    def get(self):
        self.setUser()
        if not (Kindergarten.check_existence_children_in_KG(KG_ID)):
            self.redirect('/addChild')
            return
        else:
            date = time.strftime("%d-%m-%Y")

            KG_info = Kindergarten.get_name_KG_CT_by_id(KG_ID)

            KG_children = Child.get_children_in_KG_id(KG_ID)
            childrenArr = []
            for child_id in KG_children:
                child_info = json.loads(Child.get_child_info(child_id))
                child = {"id": child_id, "name": child_info['first_name'] + ' ' + child_info['last_name']}
                childrenArr.append(child)

            self.template_values = {
                'date':         date,
                'children':     childrenArr,
                'KG_info':      KG_info,
                'KG_ID':        KG_ID
            }

            self.render('htmlPages/privateMessages.html')

# create new message - both private and broadcast
class addMessage(setUp):
    def get(self):
        self.setUser()
        date = time.strftime("%d-%m-%Y")
        KG_info = Kindergarten.get_name_KG_CT_by_id(KG_ID)

        KG_children = Child.get_children_in_KG_id(KG_ID)
        childrenArr = []
        for child_id in KG_children:
            child_info = json.loads(Child.get_child_info(child_id))
            child = {"id": child_id, "name": child_info['first_name'] + ' ' + child_info['last_name']}
            childrenArr.append(child)

        self.template_values = {
            'date':     date,
            'children': childrenArr,
            'KG_info':  KG_info,
            'KG_ID':    KG_ID
        }

        self.render('htmlPages/newMessage.html')

    def post(self):
        self.setUser()
        date = time.strftime("%Y-%m-%d")
        msg =   self.request.get('message')
        title = self.request.get('title')
        recipients = self.request.get('recipients')
        if(recipients == ''):
            public_msg = True
        else:
            public_msg = False

        j = {
            'msg':      msg,
            'title':    title,
            'KG_id':    KG_ID,
            'date':     date,
            'public_msg': public_msg,
            'recip_childs': recipients,
            'to_teacher': False
        }

        MSG_key = Message.create_message_from_json(json.dumps(j))
        if(MSG_key == -1):
            self.response.write('error adding new message')
            self.redirect('/messages')
            return
        else:
            j['MSG_key'] = MSG_key
            GCM.send_new_message_to_parents(json.dumps(j))
            self.redirect('/messages')
            return

# display all private messages per child
class childMessages(setUp):
    def get(self):
        self.setUser()
        self.response.out.headers['Content-Type'] = 'text/json'
        child_id = self.request.get('child_id')
        j = {
            "KG_id": KG_ID,
             "child_id": child_id
        }
        self.response.out.write(Message.get_all_private_messages_by_child_id(json.dumps(j)))

# send child information
class childInfo(setUp):
    def get(self):
        self.response.out.headers['Content-Type'] = 'text/json'
        child_id = self.request.get('child_id')

        self.response.out.write(Child.get_child_info(child_id))

# create a list of all the children + info
class contactList(setUp):
    def get(self):
        self.setUser()
        date = time.strftime("%d-%m-%Y")
        KG_children = Child.get_children_in_KG_id(KG_ID)
        childrenArr = []
        for child_id in KG_children:
            childrenArr.append(json.loads(Child.get_child_info(child_id)))

        KG_info = Kindergarten.get_name_KG_CT_by_id(KG_ID)

        self.template_values = {
                'date':         date,
                'children':     childrenArr,
                'KG_info':      KG_info,
                'KG_ID':        KG_ID
            }

        self.render('htmlPages/contactList.html')

# edit current kindergarten information
class editKG(setUp):
    def get(self):
        self.setUser()

        KG_info = json.loads(Kindergarten.get_KG_info_by_KG_id(json.dumps({'KG_id': KG_ID})))
        self.template_values = {
            'KG_info': KG_info,
        }

        self.render('htmlPages/editKG.html')

    def post(self):
        self.setUser()
        j = {
            'CT_first_name':    self.request.get('CT_first_name'),
            'CT_last_name':     self.request.get('CT_last_name'),
            'KG_name':          self.request.get('KG_name'),
            'phone_number':     self.request.get('phone_number'),
            'email_address':    KG_ID,
            'address':          self.request.get('address'),
        }

        Kindergarten.update_KG_from_json(json.dumps(j))

        self.redirect('/home')
        return

# edit child information
class editChild(setUp):
    def get(self, action):
        self.setUser()
        URL = self.request.url
        parseURL = urlparse.urlparse(URL)
        query = parseURL.query
        data = dict(urlparse.parse_qsl(query))

        child_id = data['child_id']
        child = json.loads(Child.get_child_info(child_id))

        KG_info = Kindergarten.get_name_KG_CT_by_id(KG_ID)

        self.template_values = {
            'child':    child,
            'KG_info':  KG_info,
            'KG_ID':    KG_ID
        }
        self.render('htmlPages/editChild.html')

    def post(self):
        self.setUser()
        j = {
            'child_first_name':         self.request.get('first_name'),
            'child_last_name':          self.request.get('last_name'),
            'child_id':                 self.request.get('child_id'),
            'date_of_birth':            self.request.get('date_of_birth'),
            'gender':                   self.request.get('gender'),
            'phone_number':             self.request.get('home_tel'),
            'address':                  self.request.get('address'),
            'parent1_first_name':       self.request.get('parent1_first_name'),
            'parent1_last_name':        self.request.get('parent1_last_name'),
            'parent1_phone_number':     self.request.get('parent1_phone_number'),
            'parent1_email_address':    self.request.get('parent1_email_address'),
            'parent2_first_name':       self.request.get('parent2_first_name'),
            'parent2_last_name':        self.request.get('parent2_last_name'),
            'parent2_phone_number':     self.request.get('parent2_phone_number'),
            'parent2_email_address':    self.request.get('parent2_email_address'),
            'KG_id': KG_ID
        }

        if(Kindergarten.update_entity_from_teacher_by_json(json.dumps(j))):
            self.redirect('/home')
            return

# delete current message
class messageDelete(setUp):
    def get(self, action):
        self.setUser()
        URL = self.request.url
        parseURL = urlparse.urlparse(URL)
        query = parseURL.query
        data = dict(urlparse.parse_qsl(query))

        msg = data['msg']
        Message.delete_message_by_ndb_id(int(msg))

        self.redirect('/messages')

# monthly report page
class monthlyReports(setUp):
    def get(self):
        self.setUser()
        date = time.strftime("%d-%m-%Y")

        KG_info = Kindergarten.get_name_KG_CT_by_id(KG_ID)

        self.template_values = {
                'date':         date,
                'KG_info':      KG_info,
                'KG_ID':        KG_ID
            }

        self.render('htmlPages/reports.html')

# display attendance report for given month
class report(setUp):
    def get(self):
        self.setUser()
        self.response.out.headers['Content-Type'] = 'text/json'
        month = int(self.request.get('month')) + 1
        KG_children = Child.get_children_in_KG_id(KG_ID)
        children = []
        for child_id in KG_children:
            j = {
                "child_id": child_id,
                "month": month
            }
            childval = Att.get_att_report_by_month(json.dumps(j))
            if childval == -1:
                self.response.out.write(json.dumps(''))
                return
            children.append(childval)

        self.response.out.write(json.dumps(children))




